package cn.edu.scau.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.scau.bean.ResultBean;
import cn.edu.scau.config.Audience;
import cn.edu.scau.entity.Customer;
import cn.edu.scau.entity.Manager;
import cn.edu.scau.entity.Nurse;
import cn.edu.scau.entity.RecoveryRegister;
import cn.edu.scau.entity.RecoveryTrack;
import cn.edu.scau.service.CustomerService;
import cn.edu.scau.service.ManagerService;
import cn.edu.scau.service.NurseService;
import cn.edu.scau.service.RecoveryRegisterService;
import cn.edu.scau.service.RecoveryTrackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "康复跟踪控制器")
@RestController
@Controller
@RequestMapping("recoveryTrack")
public class RecoveryTrackController {
	@Autowired
	RecoveryTrackService recoveryTrackService;
	@Autowired
	NurseService nurseService;
	@Autowired
	ManagerService managerService;
	@Autowired
	RecoveryRegisterService recoveryRegisterService;
	@Autowired
	CustomerService  customerService;
	@Autowired
	private Audience audience;//?
	
	/**
	 * 显示所有康复跟踪信息
	 * @return
	 */
	@ApiOperation(value = "显示所有信息页面:数据存储在hospital中")
    @GetMapping(value = "/list")
    public ResultBean list(){
        List<RecoveryTrack> recoveryTrackServices = recoveryTrackService.selectAll();
        System.out.println("请求所有登记数据："+recoveryTrackServices);
        ResultBean r = new ResultBean(200,true,"查询所有登记信息成功",recoveryTrackServices);
        return r;
    }
	
	/**
	 * 根据护士编号显示所有跟踪信息
	 * @return
	 */
	@ApiOperation(value = "显示所有信息页面:数据存储在hospital中")
    @GetMapping(value = "/nurseList/{userAccount}")
    public ResultBean nurseList(@PathVariable("userAccount") String userAccount){
		Manager manager = managerService.selectByUserAccount(userAccount);
		Nurse nurse = nurseService.selectByUserId(manager.getUserId());
        List<RecoveryTrack> recoveryTrackServices = recoveryTrackService.selectWithNurseID(nurse.getNurseid());
        System.out.println("请求所有登记数据："+recoveryTrackServices);
        ResultBean r = new ResultBean(200,true,"查询所有登记信息成功",recoveryTrackServices);
        return r;
    }
	
	/**
	 * 根据主键查询康复跟踪
	 * @param recoveryRegisterID
	 * @param recoveryTrackDate
	 * @return
	 */
	@GetMapping(value = "/{id}/{date}")
	public ResultBean findByID(@PathVariable("id") Integer recoveryRegisterID,@PathVariable("date") Date recoveryTrackDate ){
		ResultBean r = null;
		RecoveryTrack recoveryTrack = recoveryTrackService.selectByPrimaryKey(recoveryTrackDate, recoveryRegisterID);
		if(recoveryTrack==null) {
			r = new ResultBean(500,false,"查询登记信息失败",null);
		}
		else {
			r = new ResultBean(200,true,"查询登记信息成功",recoveryTrack);
		}
		return r;
	}
	
	/**
	 * 根据康复登记编号检测对应客户的客户名
	 * @param recoveryRegisterID
	 * @return
	 */
	@GetMapping(value = "/checkRecoveryRegisterID/{id}")
	public ResultBean findByID(@PathVariable("id") Integer recoveryRegisterID){
		ResultBean r = null;
		RecoveryRegister recoveryRegister = recoveryRegisterService.selectByPrimaryKey(recoveryRegisterID);
		if(recoveryRegister==null) {
			r = new ResultBean(500,false,"找不到编号为"+recoveryRegisterID+"的康复登记",null);
			return r;
		}
		Customer customer = customerService.selectByPrimaryKey(recoveryRegister.getCustomerID());
		if(customer==null) {
			r = new ResultBean(500,false,"该编号的康复登记已失效",null);
			return r;
		}
		else {
			if(customer.getCustomeruseflag()==false) {
				r = new ResultBean(500,false,"该编号的康复登记已失效",null);
				return r;
			}
		}
		r = new ResultBean(200,true,"查找客户名成功",customer.getCustomername());
		return r;
	}
	
	/**
	 * 新增康复跟踪
	 * @param recoveryTrack
	 * @param bindingResult
	 * @return
	 */
	@PostMapping(value = "/insert")
    public ResultBean insert(@Validated RecoveryTrack recoveryTrack, BindingResult bindingResult) {
        ResultBean r = null;
        if(bindingResult.hasErrors()){
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
                 ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            return r;
        }
        
        RecoveryRegister recoveryRegister = recoveryRegisterService.selectByPrimaryKey(recoveryTrack.getRecoveryRegisterID());
        if(recoveryRegister==null) {
        	r =new ResultBean(5005,false,"康复登记编号不存在",null);
        	return r;
        }//外键约束
        
        if(recoveryTrackService.selectByPrimaryKey(recoveryTrack.getRecoveryTrackDate(), recoveryTrack.getRecoveryRegisterID())!=null) {
        	r =new ResultBean(5005,false,"已经有对应日期和康复编号的信息",null);
        	return r;
        }
        
        boolean flag = recoveryTrackService.insert(recoveryTrack);
        if(flag){
        	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            r =new ResultBean(200,true,"成功新增康复登记编号为"+recoveryTrack.getRecoveryRegisterID()+"\n时间为"+sdf.format(recoveryTrack.getRecoveryTrackDate())+"的康复跟踪记录",null);
        }else
        {
            r =new ResultBean(5005,false,"增加失败",null);
        }
        return r;
    }
	
	/**
	 * 修改康复跟踪信息
	 * @param recoveryRegisterID
	 * @param RecoveryTrackDate
	 * @param recoveryTrack
	 * @param bindingResult
	 * @return
	 */
	@PutMapping(value = "/update/{id}/{date}")
    public ResultBean update(@PathVariable("id") Integer recoveryRegisterID,@PathVariable("date") Date RecoveryTrackDate,@Validated RecoveryTrack recoveryTrack, BindingResult bindingResult) {
        ResultBean r = null;
        if(bindingResult.hasErrors()){
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
            ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            return r;
        }
        
        RecoveryRegister recoveryRegister = recoveryRegisterService.selectByPrimaryKey(recoveryTrack.getRecoveryRegisterID());
        if(recoveryRegister==null) {
        	r =new ResultBean(5005,false,"康复登记编号不存在",null);
        	return r;
        }//外键约束
        
        if(recoveryTrack.getRecoveryTrackDate().compareTo(RecoveryTrackDate)!=0) {
        	if(recoveryTrackService.selectByPrimaryKey(recoveryTrack.getRecoveryTrackDate(), recoveryTrack.getRecoveryRegisterID())!=null) {
            	r =new ResultBean(5005,false,"已经有对应日期和康复编号的信息",null);
            	return r;
            }
        }
        
        
        boolean flag = recoveryTrackService.update(recoveryTrack);
        if(flag){
            r =new ResultBean(200,true,"修改成功",null);
        }else
        {
            r =new ResultBean(5005,false,"修改失败",null);
        }
        return r;
    }
	
	
	/**
	 * 根据主键删除康复跟踪
	 * @param recoveryRegisterID
	 * @param RecoveryTrackDate
	 * @return
	 */
	@DeleteMapping(value = "/delete/{id}/{date}")
    public ResultBean delete(@PathVariable("id") Integer recoveryRegisterID,@PathVariable("date") Date RecoveryTrackDate){
        ResultBean r = null;
        boolean flag = recoveryTrackService.delete(RecoveryTrackDate, recoveryRegisterID);
        if(flag){
            r =new ResultBean(200,true,"删除成功",null);
        }else
        {
            r =new ResultBean(5005,false,"删除失败",null);
        }
        return r;
    }
	
	/**
	 * 根据记录日期、康复登记编号、客户名组合查询
	 * @param RecoveryTrackDate
	 * @param recoveryRegisterID
	 * @param customerName
	 * @return
	 * @throws ParseException 
	 */
//	@ApiOperation(value = "根据模糊查询,数据存储在office中")
//  @ApiImplicitParams(value = {
//          @ApiImplicitParam(paramType = "query" ,name = "id" , value = "编号",dataType = "int"),
//          @ApiImplicitParam(paramType = "query" ,name = "name" , value = "名称",dataType = "String"),
//          @ApiImplicitParam(paramType = "query" ,name = "type" , value = "类型",dataType = "String")
//  })
	@GetMapping(value = "/find")
    public ResultBean find(String recoveryTrackDate,Integer recoveryRegisterID,String customerName) throws ParseException{
		Date date = null;
		if(!StringUtils.isBlank(recoveryTrackDate)){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			date = sdf.parse(recoveryTrackDate);
        }
        List<RecoveryTrack> recoveryTracks = recoveryTrackService.find(date, recoveryRegisterID, customerName);
        ResultBean r = new ResultBean(200,true,"组合模糊查询登记信息成功",recoveryTracks);
		return r;
    }
	
	
	@GetMapping(value = "/nurseFind/{userAccount}")
    public ResultBean find(@PathVariable("userAccount") String userAccount,String recoveryTrackDate,Integer recoveryRegisterID,String customerName) throws ParseException{
		Manager manager = managerService.selectByUserAccount(userAccount);
		Nurse nurse = nurseService.selectByUserId(manager.getUserId());
		Date date = null;
		if(!StringUtils.isBlank(recoveryTrackDate)){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			date = sdf.parse(recoveryTrackDate);
        }
        List<RecoveryTrack> recoveryTracks = recoveryTrackService.findWithNurseID(date, recoveryRegisterID, customerName, nurse.getNurseid());
        ResultBean r = new ResultBean(200,true,"组合模糊查询登记信息成功",recoveryTracks);
		return r;
    }
	
}
